<script setup lang="ts">
import { ref, computed, watch } from "vue";
import { useDark, useECharts } from "@pureadmin/utils";
import { IBarData } from "@/views/cluster/data";

// 兼容dark主题
const { isDark } = useDark();
let theme = computed(() => {
  return isDark.value ? "dark" : "default";
});

// 初始化ECharts
const chartRef = ref();
const { setOptions } = useECharts(chartRef, { theme });

const props = defineProps<{
  barData: IBarData;
}>();

const colors = ["#37A2DA", "#e06343", "#37a354", "#b55dba"];
const getRandomInt = (min, max) => {
  min = Math.ceil(min);
  max = Math.floor(max);
  return Math.floor(Math.random() * (max - min + 1)) + min;
};
const getRandomColor = () => {
  return colors[getRandomInt(0, 3)];
};

// 根据配置项渲染ECharts
const renderChart = barData => {
  let randomColor = getRandomColor();
  setOptions({
    tooltip: {
      trigger: "axis",
      axisPointer: {
        type: "shadow"
      }
    },
    grid: {
      left: "3%",
      right: "4%",
      bottom: "3%",
      containLabel: true
    },
    xAxis: [
      {
        type: "category",
        data: ["Cluster0", "Cluster1", "Cluster2", "Cluster3"],
        axisTick: {
          alignWithLabel: true
        }
      }
    ],
    yAxis: [
      {
        type: "value"
      }
    ],
    series: [
      {
        name: barData.seriesName,
        type: "bar",
        barWidth: "10%",
        data: barData.data,
        color: randomColor
      }
    ]
  });
};

// 初始渲染
renderChart(props.barData);

// 监听数据变化重新渲染
/* eslint-disable prettier/prettier */
watch(() => props.barData, (newData) => {
  renderChart(newData);
});
</script>

<template>
  <div ref="chartRef" style="width: 100%; height: 35vh" />
</template>
